package org.example.blogger.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.example.blogger.constant.Constants;


import java.security.Key;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtils {
    private  static final long JWT_EXPIRATION = 1000*60*60;
    private  static final String secretStr = "adasdwfnweiufhrwrwnwfjsdwtrwrwzhesmmmdadqwrrwfsfz";
    private  static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));

    public static String genJwtToken(Map<String,Object> claim){
        String token = Jwts.builder()
                .setClaims(claim) //存储内容
                .setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION)) //有效时间
                .signWith(key) // 进行签名
                .compact(); //生存token
        return token;
    }

    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();//使用相同的密钥
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();//解析验证
        }catch (Exception e){
            log.error("解析token失败,token:{}",token);
            return null;
        }
        return claims;
    }

    public static Integer getIdByToken(String token){
        Claims claims = parseToken(token);
        if (claims != null) {
            Integer userId =(Integer)claims.get(Constants.TOKEN_ID);
            if (userId >0){
                return userId;
            }
        }
        return  null;
    }
}
